// miniprogram/pages/index/index.js
const app = getApp()
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: '',
    open: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this

    var nickName = ''
    wx.getUserInfo({
      success: function (res) {
        var userInfo = res.userInfo
        nickName = userInfo.nickName
        var avatarUrl = userInfo.avatarUrl
        var gender = userInfo.gender //性别 0：未知、1：男、2：女
        var province = userInfo.province
        var city = userInfo.city
        var country = userInfo.country
        that.setData({ userInfo })
        console.log(userInfo)


        wx.cloud.callFunction({
          name: 'login',
          data: {},
          success: res => {
            console.log('[云函数] [login] user openid: ', res.result.openid)
            app.globalData.openid = res.result.openid

            db.collection('users').where({
              _openid: res.result.openid // 填入当前用户 openid
            }).count({
              success: function (res) {
                if (res.total === 0) {
                  db.collection('users').add({
                    // data 字段表示需新增的 JSON 数据
                    data: {
                      nickName,
                      loginTime: that.getTimeString(),
                    }
                  })
                    .then(res => {
                      console.log(res)
                    })
                    .catch(console.error)
                }
              },
              fail: console.error
            })
          },
          fail: err => {
            console.error('[云函数] [login] 调用失败', err)
          }
        })
      }
    })
  },

  getTimeString: function () {
    const year = new Date().getFullYear()
    const month = new Date().getMonth()
    const date = new Date().getDate()
    const hour = new Date().getHours()
    const minutes = new Date().getMinutes()
    return year + "-" + (month + 1) + '-' + date + ' ' + hour + ":" + minutes
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  checkboxChange: function () {
    const { open } = this.data
    this.setData({ open: !open })
  },
  formSubmit: function (e) {
    const { open } = this.data
    const { value: { name, content, number, type } } = e.detail
    const that = this
    wx.showModal({
      title: open ? "公开上传?" : "私密上传?",
      success(res) {
        if (res.confirm) {
          that.update(name, content, number, open, type)
        }
      }
    })
  },
  update: function (name, content, number, open, type) {
    const that = this
    if (!name || !content) {
      wx.showToast({
        title: "有未填項",
        icon: "none"
      })
      return false
    }

    db.collection('types').where({
     type
    }).count({
      success: function (res) {
        if (res.total === 0) {
          db.collection('types').add({
            // data 字段表示需新增的 JSON 数据
            data: {
              type,
              count: 0
            }
          })
            .then(res => {
              console.log(res)
            })
            .catch(console.error)
        } else {
          db.collection('types').where({
            type
          }).get().then(res => {
            console.log(res)
            db.collection('types').doc(res.data[0]._id).update({
              data: {
                count: res.data[0].count + 1
              },
            })
          })
        }
      },
      fail: console.error
    })

    db.collection('logs').add({
      // data 字段表示需新增的 JSON 数据
      data: {
        content,
        name,
        createTime: that.getTimeString(),
        open,
        like: 0,
        nolike: 0,
        number,
        type

      }
    })
      .then(res => {
        wx.showToast({
          title: "上传成功!",
          icon: "none"
        })
        that.formReset()
      })
      .catch(console.error)

  },
  formReset: function () {
    this.setData({
      content: '',
      name: '',
      type: ""
    })
  },
  primary: function () {

  }
})